package com.example.unique

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.example.unique.database.DatabaseHelper

class LoginActivity:AppCompatActivity() {
    private lateinit var dbHelper: DatabaseHelper
    private lateinit var enter:Button
    private lateinit var sno:EditText
    private lateinit var password:EditText
    private lateinit var forget:Button
    private lateinit var register:Button
    private var count=0
    private lateinit var getRegisterInfo: ActivityResultLauncher<Intent>
    @SuppressLint("MissingInflatedId", "Range")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.login)
        enter=findViewById(R.id.enter)
        sno=findViewById(R.id.sno)
        password=findViewById(R.id.password)
        forget=findViewById(R.id.forgetPassword)
        register=findViewById(R.id.register)
        dbHelper = DatabaseHelper(this)
        getRegisterInfo = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == 1) {
                val snoFromRegister = result.data?.getStringExtra("sInfo")
                sno.setText(snoFromRegister)
            }
        }
        enter.setOnClickListener {
            val snoInfo = sno.text.toString().trim()
            val passwordInfo = password.text.toString().trim()
            when {
                dbHelper.isUserExist(snoInfo) -> { // 检查学号是否存在
                    if (dbHelper.checkUser(snoInfo, passwordInfo)) {
                        // 获取用户信息
                        val db = dbHelper.readableDatabase
                        val cursor = db.rawQuery("SELECT academy, club, role FROM User WHERE sno = ?", arrayOf(snoInfo))
                        if (cursor.moveToFirst()) {
                            val club = cursor.getString(cursor.getColumnIndex("club"))
                            val role = cursor.getInt(cursor.getColumnIndex("role"))
                            cursor.close()

                            // 创建 Intent 并传递数据
                            val intent = Intent(this, MainActivity::class.java)
                            intent.putExtra("club", club)
                            intent.putExtra("role", role)
                            intent.putExtra("sno", snoInfo)
                            startActivity(intent)
                            finish()
                        }
                    } else {
                        Toast.makeText(this, "密码错误！", Toast.LENGTH_SHORT).show()
                        count++
                        if (count >= 3) {
                            showResetPasswordDialog(snoInfo)
                            count=0
                        }
                    }
                }
                else -> {
                    Toast.makeText(this, "用户不存在", Toast.LENGTH_SHORT).show()
                    //弹出对话框询问是否需要注册用户
                    AlertDialog.Builder(this)
                        .setMessage("用户不存在，是否需要注册用户？")
                        .setPositiveButton("是"){_,_ ->
                            val intent = Intent(this, RegisterActivity::class.java)
                            getRegisterInfo.launch(intent)
                        }
                        .setNegativeButton("否", null)
                        .show()

                }
            }

        }

        register.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            getRegisterInfo.launch(intent)
        }
    }
    // 显示重置密码的弹出框
    private fun showResetPasswordDialog(snoInfo: String) {
        AlertDialog.Builder(this)
            .setTitle("重置密码")
            .setMessage("您已经连续输错三次密码，是否需要重置密码？")
            .setPositiveButton("是") { _, _ ->
                resetPassword(snoInfo)
            }
            .setNegativeButton("否", null)
            .show()
    }

    // 执行重置密码的逻辑
    private fun resetPassword(snoInfo: String) {
        val input = EditText(this)
        AlertDialog.Builder(this)
            .setTitle("请输入新密码：")
            .setView(input)
            .setPositiveButton("完成") { dialog, _ ->
                val newPassword = input.text.toString()
                if (newPassword.isNotEmpty()) {
                    dbHelper.updatePassword(snoInfo, newPassword)
                } else {
                    AlertDialog.Builder(this)
                        .setMessage("新密码不能为空!")
                        .setPositiveButton("完成", null)
                        .show()
                }
            }
            .show()
        Toast.makeText(this, "密码已修改，请重新登录", Toast.LENGTH_SHORT).show()

    }

}